<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools>
        <!-- 自定义左侧内容 -->

        <template #slot-left>
          <span>共 {{ total }} 条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <el-button v-power="'import'" type="danger" size="small" @click="$router.push('/excel')">导入excel</el-button>
          <el-button v-power="'export'" type="success" size="small" @click="handDownload">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>

      </page-tools>

      <!-- 员工列表区域 -->
      <el-card style="margin-top: 10px;">

        <!-- 表格区域 -->
        <el-table
          :data="employeesList"
          style="width: 100%"
          border
          :default-sort="{prop:'workNumber',order:'descending'}"
        >
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" />
          <!-- <el-table-column prop="staffPhoto" label="头像"> -->
          <!-- <template v-slot="scope"> -->
          <!-- <img :src="scope.row.staffPhoto" class="staffPhoto"> -->
          <el-table-column label="头像" width="80" prop="staffPhoto">
            <template v-slot="scope">
              <image-holder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <!-- </template> -->
          <!-- </el-table-column> -->
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" :formatter="formatter" label="聘用形式" />
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable>
            <template v-slot="scope">
              <span>{{ scope.row.timeOfEntry | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="correctionTime" label="转正时间" sortable>
            <template v-slot="scope">
              <span>{{ scope.row.correctionTime | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="setRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmp(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[5, 10, 15, 30]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>

        <!-- 新增员工弹框组件 -->
        <el-dialog title="新增员工" :visible.sync="showDialog" @close="closeDialog">
          <emp-dialog ref="addEmp" @close="showDialog = false" @updata-list="updataList" />
        </el-dialog>

        <!-- 设置角色组件弹框 -->
        <el-dialog
          title="分配角色"
          :visible.sync="showRoleDialog"
          width="50%"
        >
          <!-- 设置角色组件 -->
          <assign-role v-if="showRoleDialog" :role-id="roleId" @close="showRoleDialog = false" />
        </el-dialog>

      </el-card>
    </div>
  </div>
</template>

<script>
import AssignRole from './assignRole'
import { getEmployeeList, delEmployee } from '@/api/employees'
import PageTools from '@/components/PageTools'
import EmpDialog from './empDialog.vue'
import dayjs from 'dayjs'

// 引入枚举数据
import EmployeeEnum from '@/components/constant/employees'
export default {
  name: 'Employees',
  components: {
    PageTools,
    EmpDialog,
    AssignRole
  },

  // 格式化时间
  filters: {
    formatTime(value) {
      return dayjs(value).format('YYYY-MM-DD')
    }
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 5 // 每页条数
      },
      employeesList: [], // 员工列表
      total: 0, // 数据总条数
      showDialog: false, // 添加员工组件的展示
      showRoleDialog: false,
      roleId: ''
    }
  },

  // 初始化
  created() {
    this.getEmployeeList()
  },

  methods: {
    // 分配角色
    setRole(id) {
      this.showRoleDialog = true
      this.roleId = id
    },

    // showRoleDialog() {},

    transData(rows) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 格式化表头
      // ['id','username',......]
      const headerArr = Object.keys(rows[0]) // 获取对象里的键
      const header = headerArr.map(item => {
        return map[item]
      })

      // 格式化具体数据
      const data = rows.map(item => {
        return Object.values(item)
      })
      return { header, data }
    },

    // 点击导出文件事件
    async handDownload() {
      const res = await getEmployeeList(this.query)
      console.log(res)
      const excelObj = this.transData(res.data.rows)

      import('@/vendor/Export2Excel').then(excel => {
        // const tHeader = ['英雄名称', '排行']
        // const data = [
        //   ['刘备', 100],
        //   ['关羽', 500]
        // ] // 具体数据 必填

        // 调用文件
        excel.export_json_to_excel({
          header: excelObj.header, // 表头 必填
          data: excelObj.data, // 具体数据 必填
          filename: '员工列表', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },

    // 监听弹窗关闭事件
    closeDialog() {
      // console.log(this.$refs.addEmp)
      this.$refs.addEmp.clearForm()
    },

    // 点击了确定
    updataList() {
    // 关闭弹窗
      this.showDialog = false
      // 更新页面
      this.getEmployeeList()
    },

    // 删除员工
    async delEmp(id) {
      const confirmRes = await this.$confirm('是否要删除此员工?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmRes === 'cancel') return this.$message('您已取消删除')

      const res = await delEmployee(id)
      // 当前数据只剩一条 再删除就让页码减一
      if (this.employeesList.length === 1) {
        this.query.page--

        if (this.query.page <= 0) {
          this.query.page = 1
        }
      }

      // 提示
      this.$message.success(res.message)
      // 更新页面数据
      this.getEmployeeList()
    },

    // 枚举数据
    formatter(row, column, cellValue, index) {
      // console.log(cellValue)
      const obj = EmployeeEnum.hireType.find(item => item.id === Number(cellValue))

      return obj ? obj.value : '未知'
    },

    // 获取员工列表
    async getEmployeeList() {
      const res = await getEmployeeList(this.query)
      // console.log(res)
      this.employeesList = res.data.rows
      this.total = res.data.total
    },

    // 每页显示的条数发生改变时触发
    handleSizeChange(newSize) {
      this.query.size = newSize
      // console.log(this.query.size)
      this.getEmployeeList()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeeList()
    }

  }
}
</script>

<style lang="scss" scoped>
.staffPhoto {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}</style>
